<template>
  <div class="convenient-service">
    <img src="@/assets/images/word-cloud.png" alt="">
    <div class="cloud-item" v-for="(word, index) in words" :key="index">{{ word }}</div>
  </div>
</template>
<script>
const color = ['#F9940A', '#22DFE9', '#48D446', '#7A75D6', '#003CFF', '#FDD42F']
const words = [
  '纠纷调解', '紧急求助', '安防宣传', '反诈指导', '失物招领', '矛盾纠纷', '法律咨询', '安防宣传'
]
const maxFontSize = 30;
const minFontSize = 16;
export default {
  name: 'ConvenientService',
  data() {
    return {
      words,
      occupiedPositions: [],
      wordCloudTimer:null
    }
  },
  methods: {
    async setDynamicState() {
      await this.$nextTick();
      this.occupiedPositions=[];
      const documents = document.querySelectorAll('.cloud-item')
      for (const item of documents) {
        item.style.color = color[Math.floor(Math.random() * color.length)]
        const size = Math.floor(Math.random() * (maxFontSize - minFontSize + 1)) + minFontSize;
        item.style.fontSize = size + 'px';
        const { x, y } = this.getNonOverlappingPosition(item);
        item.style.left = x + 'px';
        item.style.top = y + 'px';
        item.dataset.left = x;
        item.dataset.top = y;
      }
    },
    isOverlapping(x, y, element) {
      const wordWidth = element.offsetWidth;
      const wordHeight = element.offsetHeight;

      for (let pos of this.occupiedPositions) {
        const distX = Math.abs(pos.x - x);
        const distY = Math.abs(pos.y - y);

        if (distX < (wordWidth + pos.width) / 2 && distY < (wordHeight + pos.height) / 2) {
          return true;
        }
      }
      return false;
    },
    getNonOverlappingPosition(element) {
      const parent = document.querySelector('.convenient-service');
      const parentWidth = parent.offsetWidth;
      const parentHeight = parent.offsetHeight;
      let x, y;
      let isValid = false;
      const wordWidth = element.offsetWidth;
      const wordHeight = element.offsetHeight;

      while (!isValid) {
        x = Math.floor(Math.random() * (parentWidth * 0.7))+(parentWidth * 0.1);
        y = Math.floor(Math.random() * (parentHeight * 0.73))+(parentWidth * 0.1);
        isValid = !this.isOverlapping(x, y, element);
      }
      this.occupiedPositions.push({ x, y, width: wordWidth, height: wordHeight});
      return {x, y};
    },
  },
  beforeDestroy() {
    this.wordCloudTimer && clearInterval(this.wordCloudTimer)
  },
  mounted() {
    this.setDynamicState()
    this.wordCloudTimer=setInterval(()=>{
      this.setDynamicState()
    },5000)
  }
}
</script>
<style scoped lang="scss">
.convenient-service {
  width: 100%;
  height: 100%;
  position: relative;

  img {
    width: 75%;
    position: absolute;
    transform: translate(-50%, -50%);
    left: 50%;
    top: 50%;
  }

  .cloud-item {
    position: absolute;
    transform: translate(-50%, -50%);
  }
}
</style>
